package net.myspring.middle.validator;

import net.myspring.common.utils.ValidationUtils;
import net.myspring.middle.domain.Department;
import net.myspring.middle.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by liuj on 2016-08-29.
 */
@Component
public class DepartmentValidator implements Validator {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public boolean supports(Class<?> clazz) {
        return Department.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Department department = (Department) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name", "部门名称不能为空");
        Department checkDepartment = departmentMapper.findByName(department.getName());
        if (checkDepartment != null && !checkDepartment.getId().equals(department.getId())) {
            errors.rejectValue("name", "error.name", "部门名称已存在");
        }
    }
}
